import { defineStore } from "pinia";

export const useThemeStore = defineStore("theme", {
  state: () => ({
    isDark: false,
  }),

  actions: {
    // 切换主题
    toggleTheme() {
      this.isDark = !this.isDark;
      this.applyTheme();
      this.saveSettings();
    },

    // 监听系统主题变化
    setupSystemThemeListener() {
      const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");

      // 初始化时应用系统主题
      this.isDark = mediaQuery.matches;
      this.applyTheme();

      // 监听系统主题变化
      mediaQuery.addEventListener("change", (e) => {
        // 如果没有本地存储的设置，则跟随系统主题
        if (!localStorage.getItem("theme-settings")) {
          this.isDark = e.matches;
          this.applyTheme();
        }
      });
    },

    // 保存设置到本地存储
    saveSettings() {
      localStorage.setItem(
        "theme-settings",
        JSON.stringify({
          isDark: this.isDark,
        })
      );
    },

    // 应用主题
    applyTheme() {
      document.documentElement.classList.toggle("dark", this.isDark);
    },

    // 初始化主题
    initTheme() {
      // 从本地存储加载设置
      const savedSettings = localStorage.getItem("theme-settings");
      if (savedSettings) {
        const { isDark } = JSON.parse(savedSettings);
        this.isDark = isDark;
      } else {
        // 默认跟随系统
        this.isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
      }

      this.applyTheme();
      this.setupSystemThemeListener();
    },
  },
});
